#import <Foundation/Foundation.h>
#import "AppDelegate.h"

#if !TARGET_IPHONE_SIMULATOR
#import "XssSignModule.h"

#define configFile @"BjcaConfig"
#define configPostfix @"plist"


@interface XssSignModule () <CASignAPIDelegate>
@end


@implementation  XssSignModule

RCT_EXPORT_MODULE(XssSigner);

/*  templatePdf:(NSString*)pdf contentType:(NSString*)contentType */
RCT_EXPORT_METHOD(showSignatureDialog: (NSString*)businessId
                  signer:(NSString*)signer
                  signerIdCard:(NSString*)signerIdCard
                  keywords:(NSArray*)keywordArr
                  channel: (NSString*) channel
                  metric: (NSDictionary*) metricdict
                  isLandscape: (BOOL) isLandscape
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject) {
  self.resolver = resolve;
  self.rejecter = reject;
  dispatch_async(dispatch_get_main_queue(), ^{
    [self initSignApi:channel isLandscape:isLandscape];
    [self setFormInfomation:businessId];
    [self setSignInfomation:signer index:0 idNumber:signerIdCard keywords:keywordArr metric:metricdict];
    [self showSignViewController];
  });
}


- (void) initSignApi:(NSString*) channel isLandscape:(BOOL) isLandscape {
        //1.初始化API.
    self.signApi = [[SignAPI alloc]init];
  
    //设置代理（返回签名图片，批注图片）
    self.signApi.signAPIDelegate = self;
    //true竖屏，false横屏
    self.signApi.signScreenOrientation = !isLandscape;
    self.signApi.isShouldAutorotate = false;

    //self.AVPictureView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 200, 100, 100)];
    //[self.view addSubview:self.AVPictureView];
        //2.设置渠道号.
    int CLS = [self.signApi setChannel:channel];
    if (CLS!=1) {
        NSLog(@"渠道号配置失败==%d",CLS);
    }else {
        NSLog(@"渠道号配置成功");
    }
}
/************************************************
 *  步骤3：.设置模版信息.
 ************************************************
 */
//3.设置模版信息.
- (void)setFormInfomation:(NSString*) businessId {

    self.OrigialObj = [[OrigialContentObj alloc]init];
    //设置工单号
    [self.OrigialObj setBusinessId:businessId];
    //设置对应服务端的xslt的id
    //[self.OrigialObj setDocStyleTid:@"123123"];
    //设置上传原文的格式
    [self.OrigialObj setContent_type:CONTENT_TPYE_HTML];
    //设置加密方法（需项目经理指导）
    [self.OrigialObj setServerEncType:EncType_RSA];
    //从沙盒取出原文并转化为data数据
    NSString *htmlStr= [[NSBundle mainBundle]pathForResource:@"2_new" ofType:@"html"];
    NSData *orgdata=[NSData dataWithContentsOfFile:htmlStr];
    //3.配置表单信息,orgdata为原文数据
    int CLS = [self.signApi setOrigialContent:self.OrigialObj mydata:orgdata];
    if (!CLS) {
        NSLog(@"模版配置失败");
    }else {
        NSLog(@"模版配置成功");
    }

}
/************************************************
 *  步骤4：设置证据.
 ************************************************
 */
//4.设置证据：4.1设置录音证据
- (IBAction)setSoundEvidence:(id)sender {
    NSString *path=[[NSBundle mainBundle] pathForResource:@"bjca" ofType:@"wav"];
    NSData *soundData = [NSData dataWithContentsOfFile:path];
    //4.1设置录音证据:SOUND_SIGNER_RETELL
    int isPass = [self.signApi addEvidenceIndex:2 withSignIndex:0 contentData:soundData bioType:VIDEO_SIGNER_SIGN_ACTION];//[self.signApi addEvidence:0 contentData:soundData bioType:SOUND_SIGNER_RETELL];
    if (isPass==1) {
        NSLog(@"添加录音证据成功");
    }else {
        NSLog(@"错误码：%d",isPass);
    }
}
//4.设置证据：4.2设置图片证据
- (IBAction)setPictureEvidence:(id)sender {
    UIImage *img = [UIImage imageNamed:@"img.jpg"];
    NSData *imgData = UIImageJPEGRepresentation(img, 1.0);
    //4.2设置图片证据：PHOTO_SIGNER_IDENTITY_CARD_FRONT
    int isPass = [self.signApi addEvidenceIndex:0 withSignIndex:0 contentData:imgData bioType:PHOTO_SIGNER_IDENTITY_CARD_FRONT];//[self.signApi addEvidence:0 contentData:imgData bioType:PHOTO_SIGNER_IDENTITY_CARD_FRONT];
    if (isPass==1) {
        NSLog(@"添加图片证据成功");
    }else {
        NSLog(@"错误码：%d",isPass);
    }

    int isPass2 = [self.signApi addEvidenceIndex:1 withSignIndex:0 contentData:imgData bioType:PHOTO_SIGNER_IDENTITY_CARD_FRONT];
    if (isPass2==1) {
        NSLog(@"添加图片证据成功");
    }else {
        NSLog(@"错误码：%d",isPass2);
    }
}
/************************************************
 *  步骤5：调用批注.
 ************************************************
 */
//5.1 配置批注信息，调用接口：addCommentCaptureObj:
- (IBAction)setMassSignIntermation:(UIButton *)sender {
    //批注框信息配置
    self.massSignCapObj = [[CommentCaptureObj alloc]init];
    //此index对应批注接口的showCommentDialog:(int)index
    self.massSignCapObj.index = 0;
    //批注样式
    self.massSignCapObj.commentType = ANIMATION_STYLE;
    //签名人信息：1.姓名 2.证件类型 3.证件号码
    self.massSignCapObj.signer.UName = @"良辰";
    self.massSignCapObj.signer.IDNumber = @"342921199308301111";
    self.massSignCapObj.signer.IDType = TYPE_IDENTITY_CARD;
    self.massSignCapObj.distinguishErrorText = @"识别错误提示语";//识别错误提示语，默认“识别错误”.
    //签名规则：0关键字签名,1坐标,2Tid
    self.massSignCapObj.signRule.RuleType = @"0";
    self.massSignCapObj.signRule.KWRule.KW = @"甲方签字";
    //决定在第几页搜寻关键字
    self.massSignCapObj.signRule.KWRule.Pageno = @"-1";
    //搜寻当页的第几个关键字
    self.massSignCapObj.signRule.KWRule.KWIndex = @"1";
    //相对关键字的偏移量设置
    self.massSignCapObj.signRule.KWRule.XOffset = @"10";
    self.massSignCapObj.signRule.KWRule.YOffset = @"10";

    //坐标设置时配置XYZRule
//    self.massSignCapObj.signRule.XYZRule.Left=@"20";
//    self.massSignCapObj.signRule.XYZRule.Right=@"80";
//    self.massSignCapObj.signRule.XYZRule.Top=@"80";
//    self.massSignCapObj.signRule.XYZRule.Bottom=@"20";
//    self.massSignCapObj.signRule.XYZRule.Pageno=@"1";
    //规则号设置时配置
//    self.massSignCapObj.signRule.Tid = @"1234";

    //设置笔迹颜色
    [self.massSignCapObj setStrokeColor:[UIColor redColor]];
    //设置笔迹粗细
    [self.massSignCapObj setStrokeWidth:10.0];
    //设置图片大小（按照实际签名图片计算）
    self.massSignCapObj.SignImageSize = CGSizeMake(600, 200);
    //设置批注文字
    self.massSignCapObj.commitment = @"保险条款，产品说明书和投保提示书，了解本产品的特点和保单利益的不确定性";
    //保险条款，产品说明书和投保提示书，了解本产品的特点和保单利益的不确定性。
    //@"这样就没，问题咯这样，没有问题咯这样，没有问题。这样有问题咯这样，问题咯这样。";
    //设置生成图片每行最多多少个字
    self.massSignCapObj.lineMax = 12;
    //设置是否开启时间戳，对应服务器端配置
    self.massSignCapObj.IsTSS = @"false";
    //配置识别属性开启识别
    self.massSignCapObj.isdistinguish = false;
    //批注
    self.massSignCapObj.isShowBgText = true;
    self.massSignCapObj.editBarTextSize = 18;
    self.massSignCapObj.editBarTextColor = [UIColor yellowColor];
    self.massSignCapObj.currentEditBarTextColor = [UIColor orangeColor];
        self.massSignCapObj.currentEditBarTextSize = 1.5;
    self.massSignCapObj.ocrErrorTime = 3;
    //调用配置批注信息接口
    int CLS = [self.signApi addCommentCaptureObj:self.massSignCapObj];
    if (CLS != 1) {
        NSLog(@"error %d",CLS);
    }else {
        NSLog(@"签名配置成功");
    }
}
/************************************************
 *  步骤6：调用签名.
 ************************************************
 */
//6.1配置签名信息，调用：addSignCaptureObj

- (void)setSignInfomation:(NSString *)name index:(int)signindex idNumber:(NSString *)number
    keywords:(NSArray*)keywords
    metric: (NSDictionary*)metric {
    //签名框信息配置
    self.signCaptureObj = [[SignCaptureObj alloc]init];
    //此index对应签名接口的showSignatureDialog:(int)index
    self.signCaptureObj.index = signindex;
    //签名人信息：1.姓名 2.证件类型 3.证件号码
    self.signCaptureObj.signer.UName = name;
    self.signCaptureObj.signer.IDType =TYPE_IDENTITY_CARD ;
    self.signCaptureObj.signer.IDNumber = number;
    self.signCaptureObj.distinguishErrorText = @"姓名识别错误----";//识别错误提示语，默认“识别错误”.
    //self.signCaptureObj.agentName = @"胖虎";//ocr识别的名字，如果不设置ocr识别的就是name这个属性。

    //设置签名人是否必须完成签名才允许打包, 默认NO
    self.signCaptureObj.necessary = YES;
    self.signCaptureObj.signRuleArray = [NSMutableArray arrayWithCapacity:0];
    self.signCaptureObj.signRule.RuleType = @"0";
    self.signCaptureObj.signRule.KWRule.KW = keywords[0];
    self.signCaptureObj.signRule.KWRule.Pageno = @"-1";
    self.signCaptureObj.signRule.KWRule.KWIndex = @"1";
    self.signCaptureObj.signRule.KWRule.XOffset  = @"10";
    self.signCaptureObj.signRule.KWRule.YOffset = @"10";
    for (int i = 0; i < keywords.count; i++) {
      SignRule* rule = [[SignRule alloc]init];
      rule.RuleType = @"0";
      rule.KWRule.KW = keywords[i];
      rule.KWRule.Pageno = @"-1";
      rule.KWRule.KWIndex = @"1";
      rule.KWRule.XOffset = [NSString stringWithFormat:@"%@", [metric objectForKey:@"xoffset"]]; //@"20";
      rule.KWRule.YOffset = [NSString stringWithFormat:@"%@",[metric objectForKey:@"yoffset"]];//@"10";
      NSLog(@"%@", rule.KWRule);
      [self.signCaptureObj.signRuleArray addObject:rule];
    }
  /*
  //签名规则：0关键字签名,1坐标,2Tid
    self.signCaptureObj.signRule.RuleType = @"0";
    self.signCaptureObj.signRule.KWRule.KW = @"甲方签字";
    //决定在第几页搜寻关键字
    self.signCaptureObj.signRule.KWRule.Pageno = @"1";
    //搜寻当页的第几个关键字
    self.signCaptureObj.signRule.KWRule.KWIndex = @"1";

    self.signCaptureObj.signRule.KWRule.XOffset = @"10";
    self.signCaptureObj.signRule.KWRule.YOffset = @"10";
*/
    //坐标设置时配置XYZRule
//    self.signCaptureObj.signRule.XYZRule.Left=@"20";
//    self.signCaptureObj.signRule.XYZRule.Right=@"80";
//    self.signCaptureObj.signRule.XYZRule.Top=@"80";
//    self.signCaptureObj.signRule.XYZRule.Bottom=@"20";
//    self.signCaptureObj.signRule.XYZRule.Pageno=@"1";
    //规则号设置时配置
//    self.signCaptureObj.signRule.Tid = @"1234";

    //设置笔迹颜色
    [self.signCaptureObj setStrokeColor:[UIColor blackColor]];
    //设置笔迹粗细
    [self.signCaptureObj setStrokeWidth:10.0];
    //设置图片大小（按照实际签名图片计算）
    [self.signCaptureObj setSignImageSize:CGSizeMake([metric[@"imageWidth"] floatValue]/*45*/, [metric[@"imageHeight"] floatValue]/*30*/)];
    //设置是否自定义签名框
    [self.signCaptureObj setIsViewMyself:true];
    //设置是否开启时间戳，对应服务器端配置
    self.signCaptureObj.IsTSS = @"false";
    //设置提醒文字
    [self.signCaptureObj setRemindTitle:[NSString stringWithFormat: @"请签名人%@签字",name]];
    //设置从第几个字开始凸显出来
        [self.signCaptureObj setTitleSpanFromOffset:5];
    //设置到第几个字凸显结束
    [self.signCaptureObj setTitleSpanToOffset:5+(int)name.length];//5+(int)name.length

    //配置识别属性开启识别
    //self.signCaptureObj.isdistinguish = true;

    //开启签名中的拍照
    //self.signCaptureObj.isOpenSigningCamera = true;
    //关闭人脸检测
    self.signCaptureObj.closeCheckFace = true;
    //检测无人脸提示语设置
    self.signCaptureObj.checkfaceMarkedwords = @"无人脸";
/*
    self.signCaptureObj.avType = BJCAAnySign_AVType_PHOTO;
    self.signCaptureObj.avMaxTime = 10;
    self.signCaptureObj.avRemindText = @"视频拍摄完成";
    self.signCaptureObj.ocrErrorTime = 3;
 */
    self.signCaptureObj.signatureBoardType = BJCAAnySignSinglePageType; //BJCAAnySignMultiwordType BJCAAnySignWordNumberTransformType
 //调用配置签名信息接口
    int CLS=[self.signApi addSignCaptureObj:self.signCaptureObj];
    if (CLS != 1) {
        NSLog(@"error %d",CLS);
    } else {
        NSLog(@"签名配置成功");
    }
}
//6.3.调用签名框，调用：showSignatureDialog:
- (IBAction)showSignViewController {
    [self.signApi showSecurityAlertView:^(bool isAgree) {
        if (isAgree) {

            UIViewController *signController = [self.signApi showSignatureDialog:0];
            //自定义按钮事例
            if (self.signCaptureObj.isViewMyself==true) {
                signController.view.backgroundColor = [UIColor whiteColor];
                CGRect screentRect = [UIScreen mainScreen].bounds;//self.view.view.frame;
                CGFloat screenWid = screentRect.size.width;
                CGFloat screenHei = screentRect.size.height;
                //添加取消按钮
                UIButton *cancelButton = [[UIButton alloc]initWithFrame:CGRectMake(screenWid-108-10, screenHei-40-10, 108, 27)];
                [cancelButton addTarget:self.signApi action:@selector(cancleScreen) forControlEvents:UIControlEventTouchUpInside];
                [cancelButton setBackgroundImage:[UIImage imageNamed:@"SignBundle.bundle/cancel_red.png"] forState:UIControlStateNormal];
                [signController.view addSubview:cancelButton];
                //添加清屏按钮
                UIButton *clearButton = [[UIButton alloc]initWithFrame:CGRectMake(screenWid/2-108/2,screenHei-40-10,108,27)];
                [clearButton addTarget:self.signApi action:@selector(clearScreen) forControlEvents:UIControlEventTouchUpInside];
                [clearButton setBackgroundImage:[UIImage imageNamed:@"SignBundle.bundle/clear_red.png"] forState:UIControlStateNormal];
                [signController.view addSubview:clearButton];
                //添加储存按钮
                UIButton *saveButton = [[UIButton alloc]initWithFrame:CGRectMake(10,screenHei-40-10,108,27)];
                [saveButton addTarget:self.signApi action:@selector(saveScreen) forControlEvents:UIControlEventTouchUpInside];
                [saveButton setBackgroundImage:[UIImage imageNamed:@"SignBundle.bundle/ok_red.png"] forState:UIControlStateNormal];
                [signController.view addSubview:saveButton];
              
              float startWidthPos = screenWid / 2 - 70;
              NSString* name = self.signCaptureObj.signer.UName;
              UILabel* label = ({
                  UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(startWidthPos, 20, 10, 20)];
                  label.text = @"请";
                  label.textColor = [UIColor grayColor];
                  label.font = [UIFont systemFontOfSize:16];
                  [label sizeToFit];
                  [signController.view addSubview:label];
                  
                  label;
              });

              float label1Width = label.intrinsicContentSize.width + 7;
              UILabel* label2 = ({
                UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(startWidthPos + label1Width, 14, 50, 20)];
                  label.text = name;
                  label.textColor = [UIColor blueColor];
                  label.font = [UIFont systemFontOfSize:24 weight:UIFontWeightMedium];
                  [label sizeToFit];
                  [signController.view addSubview:label];
                  
                  label;
              });

              float label2Width = label1Width + label2.intrinsicContentSize.width + 2;
              UILabel* label3 = ({
                  UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(startWidthPos + label2Width, 20, 50, 20)];
                  label.text = @"签字";
                  label.textColor = [UIColor grayColor];
                  label.font = [UIFont systemFontOfSize:16];
                  [label sizeToFit];
                  [signController.view addSubview:label];
                  
                  label;
              });
                //适配ipad
                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
                    //横屏幕
                    if (!self.signApi.signScreenOrientation) {
                        // cancelButton.frame = CGRectMake(screenHei-108-10, screenWid-40-10, 108, 27);
                        // clearButton.frame = CGRectMake(screenHei/2-108/2,screenWid-40-10,108,27);
                        // saveButton.frame = CGRectMake(10,screenWid-40-10,108,27);
                    }
                }
            }
            if (signController) {
                [signController setModalPresentationStyle:UIModalPresentationFullScreen];
              UIViewController *appView = [UIApplication sharedApplication].keyWindow.rootViewController;
              [appView presentViewController:signController animated:YES completion:nil];
            }else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"显示失败" message:@"请检查配置参数" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                [alert show];
            }
        } else {
          self.resolver(@{});
        }
    }];
}
/************************************************
 *  步骤7：配置签章.
 ************************************************
 */
//7.配置签章信息，服务端根据配置添加签章，对应模版设置项－开启isCachet＝true
- (IBAction)starCachet:(UIButton *)sender {

    self.cachetObj = [[CachetArray alloc]init];
    self.cachetObj.Signer.UName = @"北京数字认证";
    self.cachetObj.Signer.IDType = TYPE_IDENTITY_CARD;
    self.cachetObj.Signer.IDNumber = @"211321197002082938";
    self.cachetObj.SignRule.Tid = @"10003";
    self.cachetObj.SignRule.RuleType = @"2";
    UIImage *img = [UIImage imageNamed:@"img.jpg"];
    NSData *Picdata = UIImageJPEGRepresentation(img, 1.0);
    self.cachetObj.IsTSS = @"false";
    int result = [self.signApi addChachetObj:self.cachetObj];
    if (result != 1) {
        NSLog(@"error %d",result);
    }

}

- (void)setOnSignatureResultListener:(NSDictionary *)result{
  if ([[result objectForKey:@"returnKey"] isEqualToString:@"onSaveSign"]) {
    NSString* resultCode = [result objectForKey:@"resultCode"];
    NSLog(@"onSaveSign result %@", resultCode);
    if ([resultCode intValue] == 0) {

          //通过isReadyToUpload验证数据是否正确
          int enable = [self.signApi isReadyToUpload];
          if (enable==1) {
            NSArray *signArray=[self.signApi genBatchSignRequest:self.signCaptureObj.signRuleArray];
            if (signArray.count == 0) {
                  NSLog(@"打包数据为空");
              self.rejecter(@"", @"empty sign result", nil);
              }else {
                  //UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"加密数据成功" message:nil delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                  //[alert show];
                UIImage* signImage = [result objectForKey:@"signature"];
                NSData* imageData = UIImagePNGRepresentation(signImage);
                NSString* base64Img = [imageData base64EncodedStringWithOptions:0];
                NSLog(@"base64 %@",base64Img);
                NSDictionary *dict = @{@"signEncs": signArray, @"signImgBase64": base64Img};
                //NSString *signImgPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"img.png"];
                //[imageData writeToFile:signImgPath atomically:YES];
                self.resolver(dict);
              }

          }else{
              NSLog(@"%d",enable);
          }
      [self.signApi resetApi];
    }
  } else if ([[result objectForKey:@"returnKey"] isEqualToString:@"onCancelSign"]) {
    NSLog(@"onCancelSign");
    self.resolver(@{});
  } else if ([[result objectForKey:@"returnKey"] isEqualToString:@"onClearSign"]) {
    NSLog(@"onClearSign");
  }
}
/************************************************
 *  步骤8：打包数据.
 ************************************************
 */
//8.打包数据，签单完成。调用接口：genSignRequest。
- (IBAction)getRequestBag:(id)sender {
    //通过isReadyToUpload验证数据是否正确
    int enable = [self.signApi isReadyToUpload];
    if (enable==1) {
        NSString *str=[self.signApi genSignRequest];
        if (!str) {
            NSLog(@"打包数据为空");
            return;
        }else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"加密数据成功" message:nil delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alert show];
        }
        //供参考：上传加密包（用户可修改IP地址上传至内网）
//        myhttprequest *mywebreq=[[myhttprequest alloc]init];
//        [mywebreq mySignRequestWithServer:str];
        //供参考：也可以写入document路径,对加密包进行验证和测试。
        NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
        NSString *documentDirectory = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"BjcaSpsTest.txt"];
        [data writeToFile:documentDirectory atomically:YES];
    }else{
        NSLog(@"%d",enable);
        return;

    }
}
/************************************************
 *  步骤9：清除API数据.
 ************************************************
 */
//9.清除API数据，注意：每次调用genSignRequest以后调用此接口，进行下一次签单，重复步骤2-步骤9
- (IBAction)resetData:(id)sender {
    [self.signApi resetApi];
}

@end
#endif
